<template>
  <div>
    <div class="search">
      <input v-model="keyword" class="input-search" type="text" placeholder="输入城市名或拼音">
    </div>
    <div class="search-content" ref="wrapper" v-show="keyword">
      <ul>
        <li class="item border-bottom" v-for="item in list" :key="item.id" @click="handleCityClick(item.name)">
          {{item.name}}
        </li>
        <li class="item border-bottom" v-show="listNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
  import BScroll from 'better-scroll'
  export default {
    name: 'Search',
    props: {
      cities: Object
    },
    data() {
      return {
        keyword: "",
        timer: null,
        list: []
      }
    },
    methods:{
      handleCityClick(city){
        this.$store.dispatch("changeCity",city)
        this.$router.push("/");
      }
    },
    computed:{
      listNoData(){
        return !this.list.length;
      }
    },
    mounted(){
      this.scroll = new BScroll(this.$refs.wrapper);
    },
    watch: {
      keyword() {
        const result = [];
        if (this.timer) {
          clearTimeout(this.timer);
        }
        if (!this.keyword) {
          this.list = [];
          return;
        }
        this.timer = setTimeout(() => {
          for (let i in this.cities) {
            this.cities[i].forEach((value) => {
              if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
                result.push(value)
              }
            })
          }
        }, 100);
        this.list = result;
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .search
    height .72rem
    background $bgColor
    padding 0 .1rem
    .input-search
      box-sizing border-box
      width 100%
      height .62rem
      text-align center
      color #666
      padding 0 .1rem
  .search-content
    z-index 1
    position absolute
    left 0
    right 0
    bottom 0
    top 1.58rem
    background #eee
    overflow hidden
    .item
      line-height .6rem
      padding-left .2rem
      color  #666
      background #fff
</style>
